import { modifyUserInfo } from '@/api/flow/auth';

export default {
  data() {
    return {
      form: this.$form.createForm(this),
      formLoading: false
    };
  },

  methods: {
    // form validateFields
    validateFieldsForm() {
      const validateFieldsKey = [
        'first_name',
        'last_name',
        'birthday',
        'gender',
        'unit',
        'state',
        'post_code',
        'district',
        'street',
        'driver_licence_number',
        'driver_expire_date',
        'driver_state'
      ];

      return new Promise((resolve, reject) => {
        const {
          form: { validateFieldsAndScroll }
        } = this;

        validateFieldsAndScroll(validateFieldsKey, { force: true, first: true }, (err, values) => {
          if (!err) {
            resolve(values);
            return false;
          }
          reject(false);
        });
      });
    },

    handleSubmit(e) {
      e.preventDefault();

      this.formLoading = true;

      this.validateAndSubmit()
        .then(async () => {
          this.$notification.success({
            message: 'Modified successfully!',
            duration: 1
          });

          await this.$store.dispatch('GetInfo');

          this.$router.push({
            name: 'BasicSettings'
          });
        })
        .finally(() => {
          this.formLoading = false;
        });
    },

    validateAndSubmit() {
      return new Promise((resolve, reject) => {
        this.validateFieldsForm()
          .then(() => {
            this.submitForm()
              .then(async (data) => {
                resolve(data);
              })
              .catch((error) => {
                reject(error);
              });
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // Retrieve password
    submitForm() {
      const validateFieldsKey = [
        'first_name',
        'last_name',
        'birthday',
        'gender',
        'post_code',
        'state',
        'unit',
        'district',
        'street',
        'driver_licence_number',
        'driver_expire_date',
        'driver_state'
      ];

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey);

        modifyUserInfo(fields)
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

     handleProvinceChange(value) {
      const index = this.ausState
        .findIndex(({ name_en }) => value === name_en);

      if (index > -1) {
        const { childrens } = this.ausState[index];
        this.ausDistrictAndZipCode = childrens;
        // this.secondCity = ;
        this.form.setFieldsValue({ district: childrens[0].name_en });
      }
      // this.cities = cityData[value];
      // this.secondCity = cityData[value][0];
    }
  }
};
